import re
import falcon

from WebBackend.middleware.virtualWorldGate_Chuche import login_require
from WebBackend.utils.executeCMD import execute_cmd_async

@falcon.before(login_require)
class ServiceControlAPI:
    def __init__(self, config=None):
        self.config_store = config

    async def on_get(self, req: falcon.Request, resp: falcon.Response):
        target = req.params.get('name')
        if target == 'vsftpd':
            text = await execute_cmd_async('systemctl status vsftpd', 'str')
            resp.text = text
        elif target == 'samba':
            resp.text = 'samba'
        else:
            raise falcon.HTTPNotFound()

    async def on_put(self, req: falcon.Request, resp: falcon.Response):
        target = req.params.get('name')
        if target == 'vsftpd' or 'samba':
            action = await req.get_media() or {}
            action = action.get('action')
            if action == 'start':
                fetch = await execute_cmd_async(f'systemctl start {target}')
            elif action == 'stop':
                fetch = await execute_cmd_async(f'systemctl stop {target}')
            elif action == 'restart':
                fetch = await execute_cmd_async(f'systemctl restart {target}')
            elif action == 'switch_enable':
                text = await execute_cmd_async(f'systemctl status {target}', 'str')
                if re.search(r"Loaded:.*?;\s+(enabled|disabled)", text):
                    fetch = await execute_cmd_async(f'systemctl disable {target}')
                else:
                    fetch = await execute_cmd_async(f'systemctl enable {target}')
            else:
                raise falcon.HTTPBadRequest(title="Action not found")
            resp.text = fetch
        else:
            raise falcon.HTTPNotFound(title="service not found")
